package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.common.constant.RedMoney;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppUserMapper;
import com.eco.fanliapp.dao.AppUserRewardSetupMapper;
import com.eco.fanliapp.entity.AppUserRewardSetup;
import com.eco.fanliapp.entity.SyUserMoney;
import com.eco.fanliapp.service.IAppUserRedRewardService;
import com.eco.fanliapp.service.IAppUserRewardSetupService;
import com.eco.fanliapp.service.ISyUserInvitationMoneyService;
import com.eco.fanliapp.service.ISyUserMoneyService;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.vo.RedRewardInvitationListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @date 2019-10-15
 */
@Service
public class SyUserInvitationMoneyServiceImpl implements ISyUserInvitationMoneyService {

    @Autowired
    private IAppUserRedRewardService iAppUserRedRewardService;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AppUserRewardSetupMapper appUserRewardSetupMapper;


    /**
     * 邀请收益
     *
     * @param userId
     * @param type
     * @return
     */
    @Override
    public ServerResponse invitationMakeMoney(Long userId, Integer type) {
        Map redMap = iAppUserRedRewardService.invitationMakeMoneyByUserId(userId);
        AppUserRewardSetup rewardSetup = null;
        if (redisTemplate.hasKey("AppUserRewardSetup")) {
            rewardSetup = (AppUserRewardSetup) redisTemplate.opsForValue().get("AppUserRewardSetup");
        } else {
            rewardSetup = appUserRewardSetupMapper.selectByPrimaryKey(1);
            redisTemplate.opsForValue().set("AppUserRewardSetup", rewardSetup, 1, TimeUnit.HOURS);
        }
        JSONObject json = new JSONObject();
        //已邀请人数
        int fsCount = appUserMapper.selectCountFS(userId);
        //获取粉丝列表及红包领取状态
        SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(userId);
        List<Map> list = iAppUserRedRewardService.findMoneyListHbType(userId, type);
        json.put("makeProfits", rewardSetup.getInvitationRedMoneyAmount());//立赚金额
        json.put("invitePeopleNumber", fsCount);//邀请有效人数
        json.put("waitToAccount", redMap.get("notReceived"));//等待收货，待到账
        if (syUserMoney == null) {
            json.put("canReceive", 0);//微信可提取余额
        } else {
            json.put("canReceive", syUserMoney.getCashBalanceAmount());//微信可提取余额
        }
        json.put("inviteList", list);//粉丝列表,显示两位
        return ServerResponse.createBySuccess("数据获取成功", json);
    }

    /**
     * 文案描述
     *
     * @param type
     * @return
     */
    @Override
    public ServerResponse invitationDocument(Integer type) {
        JSONObject json = new JSONObject();
        Integer participants;
        String key = null;
        json.put("firstNumber", "88");//第一名奖励金额
        json.put("secondNumber", "66");//第二名奖励金额
        json.put("thirdNumber", "33");//第三名奖励金额
        //获取当前时间
        Calendar now = Calendar.getInstance();
        String year = String.valueOf(now.get(Calendar.YEAR));
        String month = String.valueOf((now.get(Calendar.MONTH) + 1));
        String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
        if(type == 1){
             key = year + month + day + type+"countParticipants";
        }else if (type == 2){
             key = year + month + type+"countParticipants";
        }

        if (redisTemplate.opsForValue().get(key) == null) {
            participants = appUserMapper.selectCountParticipants(type);
            redisTemplate.opsForValue().set(key, participants);
        } else {
            participants = (Integer) redisTemplate.opsForValue().get(key);
        }
        json.put("participants", participants.toString());//参与人数
        return ServerResponse.createBySuccess("数据获取成功", json);
    }

    /**
     * 邀请赚钱榜单
     *
     * @param monthType 1当前月份，2上个月份
     * @return
     */
    @Override
    public ServerResponse invitationList(Long userId, Integer monthType) {
        JSONObject json = new JSONObject();
        List<RedRewardInvitationListVo> list = new ArrayList<>();
        //获取当前时间
        Calendar now = Calendar.getInstance();
        String year = String.valueOf(now.get(Calendar.YEAR));
        String month = String.valueOf((now.get(Calendar.MONTH) + 1));
        String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
        String key = year + month + day + monthType + "invitationList";
        if (redisTemplate.opsForValue().get(key) == null) {
            list = iAppUserRedRewardService.findInvitationList(monthType);
            redisTemplate.opsForValue().set(key, list);
        } else {
            list = (List<RedRewardInvitationListVo>) redisTemplate.opsForValue().get(key);
        }
        for (RedRewardInvitationListVo listVo : list
        ) {
            listVo.getPhoneNumber();
            if(listVo.getPhoneNumber() != null && !listVo.getPhoneNumber().isEmpty()){
               String phone = listVo.getPhoneNumber().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
               listVo.setPhoneNumber(phone);
            }
            if(listVo.getUserName() != null && listVo.getUserName().length()>5){
                String a = listVo.getUserName().substring(5,listVo.getUserName().length());
                if(listVo.getUserName().endsWith(a)){
                    String s1 = listVo.getUserName().substring(0, listVo.getUserName().lastIndexOf(a));
                    String name = s1 + "***";
                    listVo.setPhoneNumber(name);
                }
            }
            listVo.getUserName();
        }

        Integer state = 0;
        if (monthType == 2) {
            for (RedRewardInvitationListVo listVo : list
            ) {
                if (userId == listVo.getUserId()) {
                    state = 1;
                    break;
                }
            }
        }
        json.put("state", state);//说明
        json.put("list", list);

        return ServerResponse.createBySuccess("数据获取成功", json);
    }

    /**
     * 榜单假数据
     * @param userId
     * @param type
     * @return
     */
    @Override
    public ServerResponse invitationFakeList(Long userId, Integer type) {
        JSONObject json = new JSONObject();



        //创建假数据（上月榜单）
        List<RedRewardInvitationListVo> list  = iAppUserRedRewardService.findInvitationFakeList(type);

            list = list.subList(0,10);
            json.put("state", 0);//说明
            json.put("list", list);
            return ServerResponse.createBySuccess("数据获取成功", json);


    }



}
